<template>
  <div class="templateDesigner">
    <div class="table-container">
      <div class="g3 f16 b ks-col pl10 pb10 pt20 mb20 bb1">
        {{ value.name }}
      </div>
      <div class="pl10 pr10 tableBox">
        <el-table
          v-if="value.configJson.columns && value.configJson.columns.length"
          :data="tableData"
          style="width: calc(100% - 20px)"
          border
          @header-click="headerClick"
        >
          <el-table-column
            :label-class-name="activeHeader === i.code ? 'header-active' : ''"
            v-for="(i, index) in value.configJson.columns"
            :key="i.id + '_' + index"
            :prop="i.code"
            :fixed="i.fixed"
            :width="i.width"
          >
            <template slot="header" slot-scope="scope">
              <span
                :class="{
                  required: !!i.required && value.type === 'IMPORT',
                }"
                >{{ i.aliasName || i.name }}</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="formData" class="g3 f16 b ks-col pl10 pb10 pt20 mb20 bb1">
        {{ formTitle }}
      </div>
      <div v-if="formData" class="mr60 mb20">
        <el-form ref="form" :model="formData" label-width="140px">
          <CommonConfig
            v-model="formData"
            :type="value.type"
            v-if="type !== 'GlobalConfig'"
          />
          <component
            v-if="type"
            v-model="formData"
            :type="value.type"
            :modelId="value.modelId"
            :is="type"
          />
          <el-form-item
            v-else-if="formData.type === 'DEPARTMENT'"
            label="部门字段格式:"
          >
            <div v-if="value.type === 'IMPORT'">1.部门根据全路径匹配</div>
            <div v-if="value.type === 'IMPORT'">2.多个部门用”；“或”;“分割</div>
            <div>例：XXX公司/销售部门/销售一部;XXX公司/总经办</div>
          </el-form-item>
          <el-form-item
            v-else-if="formData.relationType === 'DICTIONARY'"
            label="数据字典格式:"
          >
            <div v-if="value.type === 'IMPORT'">1.填写字典的文本字段</div>
            <div
              v-if="
                value.type === 'IMPORT' && formData.type === 'RELATION_SELECT'
              "
            >
              2.多个数据用”；“或”;“分割
            </div>
            <div v-if="formData.type === 'RELATION_SELECT'">
              例：a标签;b标签
            </div>
            <div v-if="formData.type === 'RELATION_REFERENCE'">例：a标签</div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getHmentitymodelList } from "@/apis/paas/HmEntityModelController.js"
import GlobalConfig from "@/pages/designExcelTemplate/__components__/excelContainer/rightModel/__components__/GlobalConfig.vue"
import CommonConfig from "./__components__/CommonConfig.vue"
import DateConfig from "./__components__/DateConfig.vue"
import MoneyOrNumberConfig from "./__components__/MoneyOrNumberConfig.vue"
import RelationConfig from "./__components__/RelationConfig.vue"
import StaffConfig from "./__components__/StaffConfig.vue"
import RelationPrimaryKeyConfig from "./__components__/RelationPrimaryKeyConfig.vue"
const TYPE_ENUM = {
  DATE: "DateConfig",
  NUMBER: "MoneyOrNumberConfig",
  RELATION_SELECT: "RelationConfig",
  RELATION_REFERENCE: "RelationConfig",
  STAFF: "StaffConfig",
  RELATION_PRIMARY_KEY: "RelationPrimaryKeyConfig",
}
//关联类型字段 不可选择的字段类型
const NOT_SELECT_TYPE = [
  "STAFF", //人员
  "DEPARTMENT", //部门
  "RELATION_SELECT", //关联选择
  "RELATION_REFERENCE", //关联引用
  "ATTACHMENT", //子表
  "RELATION_PRIMARY_KEY", //关联主键
]

//人员选择字段
const staffDisplayRuleField = [
  { label: "ID", value: "id" },
  { label: "账号", value: "username" },
  { label: "用户名", value: "name" },
  { label: "工号", value: "jobNumber" },
  { label: "邮箱", value: "email" },
  { label: "电话", value: "mobile" },
  { label: "英文名", value: "englishName" },
]
export default {
  components: {
    GlobalConfig,
    CommonConfig,
    DateConfig,
    MoneyOrNumberConfig,
    RelationConfig,
    StaffConfig,
    RelationPrimaryKeyConfig,
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      activeHeader: "",
      tableData: [{}, {}, {}],
      formData: null,
      type: "",
    }
  },
  computed: {
    formTitle() {
      return this.type === "GlobalConfig" ? "全局配置" : "列配置"
    },
  },
  created() {
    // this.handelGlobalConfig();
  },
  methods: {
    computedCol() {
      const cur = this.value.configJson.columns.find(
        (i) => i.code === this.activeHeader
      )
      if (!cur) {
        this.activeHeader = ""
        this.type = ""
        this.formData = null
      }
    },
    //点击表头
    async headerClick({ property }, event) {
      if (!!property && this.activeHeader !== property) {
        this.formData = null
        this.activeHeader = property
        let formData = this.value?.configJson?.columns.find(
          ({ code }) => code === property
        )
        this.type = TYPE_ENUM[formData.type]
        //ID字段特殊处理
        if (formData.code === "id") {
          this.type = null
        }
        //关联 字典无需自定义格式
        if (formData.relationType === "DICTIONARY") {
          this.type = null
        }
        await this.intConfig(formData)
        this.formData = formData
      }
      event && event.stopPropagation()
    },
    // 初始化自定义格式，获取可选择字段list
    async intConfig(formData) {
      //导入模版 自定义格式存入filterFields字段；
      //关联引用（业务模型），关联选择（业务模型）
      if (
        ["RELATION_SELECT", "RELATION_REFERENCE"].includes(formData.type) &&
        !!formData.config
      ) {
        // 根据config内modelCode获取对应关联模型的字段list，初始赋值value
        try {
          let { modelCode } = JSON.parse(formData.config)
          let relation_modelList = []
          if (!!modelCode) {
            relation_modelList = await getHmentitymodelList({
              activated: true,
              modelKey: modelCode,
              skipRelationSelect: true,
            })
            relation_modelList = relation_modelList.filter(
              (item) => !NOT_SELECT_TYPE.includes(item.type)
            )
          }
          formData.relation_modelList = relation_modelList.map((i) => {
            return {
              ...i,
              value: i.code,
              label: i.name,
            }
          })
        } catch (error) {
          formData.relation_modelList = []
        }
      }
    },
    //全局配置
    handelGlobalConfig() {
      if (this.type === "GlobalConfig") return
      this.formData = null
      this.activeHeader = ""
      this.type = "GlobalConfig"
      this.formData = this.value
    },
    //保存
    save() {
      return new Promise((res, rej) => {
        let { configJson, key, modelId } = this.value
        if (!configJson.columns.length) {
          this.$message.warning({
            showClose: true,
            message: "请至少选择一个表头字段",
            type: "warning",
          })
          return rej("请至少选择一个表头字段")
        }
        //校验全局配置 必填
        if (!configJson.notes || !configJson.notes.trim()) {
          let tips =
            this.value.type === "IMPORT"
              ? "请配置全局配置的模版填写提示"
              : "请配置全局配置的模版导出说明"
          this.$message.warning({
            showClose: true,
            message: tips,
            type: "warning",
          })
          this.handelGlobalConfig()
          return rej(tips)
        }
        // 导入必填 重复数据判断
        if (
          this.value.type === "IMPORT" &&
          (!configJson.duplicateCheckColumns ||
            !configJson.duplicateCheckColumns.length)
        ) {
          this.$message.warning({
            showClose: true,
            message: "请配置全局配置的重复数据判断选项",
            type: "warning",
          })
          this.handelGlobalConfig()
          return rej("请配置全局配置的重复数据判断选项")
        }
        // 校验列表必填项
        const columns = []
        for (let index = 0; index < configJson.columns.length; index++) {
          let {
            id,
            code,
            type,
            aliasName,
            nullable,
            required,
            columnWidth,
            precision,
            dateFormat,
            relModelCode,
            filterFields,
            displayRule,
            relationType,
          } = configJson.columns[index]
          if (!aliasName) {
            this.$message.warning({
              showClose: true,
              message: `请配置第【${index + 1}】列的列名`,
              type: "warning",
            })
            this.headerClick({ property: code })
            return rej(`请配置第【${index + 1}】列的列名`)
          }
          // 日期自定义校验
          if (configJson.columns[index].type === "DATE" && !dateFormat) {
            this.$message.warning({
              showClose: true,
              message: `请配置列【${aliasName}】的日期格式`,
              type: "warning",
            })
            this.headerClick({ property: code })
            return rej(`请配置列【${aliasName}】的日期格式`)
          }
          //关联选择、关联引用 必填项
          if (
            ["RELATION_REFERENCE", "RELATION_SELECT"].includes(
              configJson.columns[index].type
            ) &&
            relationType !== "DICTIONARY"
          ) {
            if (this.value.type === "IMPORT") {
              if (!filterFields || !filterFields.length) {
                this.$message.warning({
                  showClose: true,
                  message: `请配置列【${aliasName}】的导入字段`,
                  type: "warning",
                })
                this.headerClick({ property: code })
                return rej(`请配置列【${aliasName}】的导入字段`)
              }
            } else {
              if (!displayRule) {
                this.$message.warning({
                  showClose: true,
                  message: `请配置列【${aliasName}】的填写规则`,
                  type: "warning",
                })
                this.headerClick({ property: code })
                return rej(`请配置列【${aliasName}】的填写规则`)
              }
            }
          }

          // 关联主键
          if (
            configJson.columns[index].type === "RELATION_PRIMARY_KEY" &&
            this.value.type === "IMPORT"
          ) {
            if (!relModelCode) {
              this.$message.warning({
                showClose: true,
                message: `请配置列【${aliasName}】的关联模型`,
                type: "warning",
              })
              this.headerClick({ property: code })
              return rej(`请配置列【${aliasName}】的关联模型`)
            }
            if (!filterFields || !filterFields.length) {
              this.$message.warning({
                showClose: true,
                message: `请配置列【${aliasName}】的导入字段`,
                type: "warning",
              })
              this.headerClick({ property: code })
              return rej(`请配置列【${aliasName}】的导入字段`)
            }
          }
          //人员必填项
          if (configJson.columns[index].type === "STAFF") {
            if (this.value.type === "EXPORT") {
              if (!displayRule) {
                this.$message.warning({
                  showClose: true,
                  message: `请配置列【${aliasName}】的填写规则`,
                  type: "warning",
                })
                this.headerClick({ property: code })
                return rej(`请配置列【${aliasName}】的填写规则`)
              }
            }
          }
          columns.push({
            id,
            code,
            type,
            columnWidth,
            dateFormat,
            precision,
            relModelCode,
            filterFields,
            displayRule,
            aliasName,
            nullable,
            required: required !== 1 ? 0 : 1,
          })
        }
        res({
          configJson: JSON.stringify({
            notes: configJson.notes,
            duplicateCheckColumns: configJson.duplicateCheckColumns,
            columns: columns,
          }),
          key,
          modelId,
        })
      })
    },
  },
}
</script>
<style lang="scss">
.templateDesigner {
  height: 100%;
  overflow: hidden;
  position: relative;

  .table-container {
    z-index: 1;
    height: 100%;
    width: 100%;
    overflow-y: auto;

    .tableBox {
      min-height: 100px;

      .deletes {
        text-decoration: line-through;
        text-decoration-color: red;
        text-decoration-style: double;
      }

      .required::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
    }
  }

  .bb1 {
    border-bottom: 1px solid #dcdfe6;
  }
}
</style>
